﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataContexts.Supplier;

public partial class Admin_Supplier_AddEdit : System.Web.UI.Page
{
    private SupplierDataContext context = new SupplierDataContext();

    public int SupplierId
    {
        get
        {
            int id = 0;

            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
                int.TryParse(Request.QueryString["id"], out id);

            return id;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ((BaseMasterPage)this.Master).CurrentPage = PageConfig.Pages.AdminSupplierAddEdit;
        if (!((BaseMasterPage)this.Master).AuthorizeCurrentUser())
            return;

        if (!IsPostBack)
        {
            LoadFuelPolicy();
            trConfirmPassword.Visible = (SupplierId == 0);
            trPassword.Visible = (SupplierId == 0);

            if (SupplierId > 0)
            {
                Supplier supplier = context.Suppliers.SingleOrDefault(obj => obj.SupplierId == SupplierId);
                //CONTROL ASSIGNMENT
                txtSupplierName.Text = supplier.SupplierName;
                txtEmailAddress.Text = supplier.EmailAddress;
                chkPayOnArrival.Checked = supplier.PayOnArrival.Value;
                txtDisplayName.Text = supplier.DisplayName;
                ddlFualPolicy.SelectedValue = supplier.FualPolicyId.Value.ToString();
                txtBookingThreshold.Text = supplier.BookingThreshold.ToString();
                txtGracePeriodMins.Text = supplier.GracePeriodMins.ToString();
                if (supplier.Navigator.HasValue)
                    chkNavigator.Checked = supplier.Navigator.Value;
                if (supplier.NavRentPrice.HasValue)
                    txtNavRentPrice.Text = supplier.NavRentPrice.Value.ToString("###.00");
                if (supplier.NavRentSellPrice.HasValue)
                    txtNavRentSellPrice.Text = supplier.NavRentSellPrice.Value.ToString("###.00");
                if (supplier.NavFixRentPrice.HasValue)
                    txtNavFixRentPrice.Text = supplier.NavFixRentPrice.Value.ToString("###.00");
                if (supplier.NavFixRentSellPrice.HasValue)
                    txtNavFixRentSellPrice.Text = supplier.NavFixRentSellPrice.Value.ToString("###.00");
                if (supplier.AddDriveRentPrice.HasValue)
                    txtAddDriveRentPrice.Text = supplier.AddDriveRentPrice.Value.ToString("###.00");
                if (supplier.AddDriveRentSellPrice.HasValue)
                    txtAddDriveRentSellPrice.Text = supplier.AddDriveRentSellPrice.Value.ToString("###.00");

                if (supplier.UserId.HasValue)
                {
                    User user = context.Users.SingleOrDefault(obj => obj.UserId == supplier.UserId.Value);
                    //CONTROL ASSIGNMENT
                    txtUsername.Text = user.Username;
                }
            }
        }
    }

    private void LoadFuelPolicy()
    {
        ddlFualPolicy.DataSource = from fp in context.FuelPolicies
                                   select new { fp.FuelPolicyId, FuelPolicy = fp.FuelPolicyName + "-" + fp.FuelPolicyDesc };

        ddlFualPolicy.DataTextField = "FuelPolicy";
        ddlFualPolicy.DataValueField = "FuelPolicyId";
        ddlFualPolicy.DataBind();

        ddlFualPolicy.Items.Insert(0, new ListItem("Select Fuel Policy", "0"));
    }
    protected void chkNavigator_CheckedChanged(object sender, EventArgs e)
    {
        rfvNavRentPrice.Enabled = chkNavigator.Checked;
        rfvNavRentSellPrice.Enabled = chkNavigator.Checked;
        txtNavRentPrice.Text = "0.0";
        txtNavRentSellPrice.Text = "0.0";
        txtNavFixRentPrice.Text = "0.0";
        txtNavFixRentSellPrice.Text = "0.0";
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        Supplier supplier = new Supplier();
        if (SupplierId > 0)
            supplier = context.Suppliers.SingleOrDefault(obj => obj.SupplierId == SupplierId);

        if (ExistsUsername(txtUsername.Text, supplier.UserId.HasValue ? supplier.UserId.Value : 0))
        {
            divError.InnerHtml = "Username \"" + txtUsername.Text + "\" is already exists, kindly choose another<br/><br/>";
            return;
        }

        supplier.SupplierName = txtSupplierName.Text;
        supplier.EmailAddress = txtEmailAddress.Text;
        supplier.PayOnArrival = chkPayOnArrival.Checked;
        supplier.DisplayName = txtDisplayName.Text;
        supplier.FualPolicyId = Convert.ToInt32(ddlFualPolicy.SelectedValue);
        supplier.BookingThreshold = Convert.ToInt32(txtBookingThreshold.Text);
        supplier.GracePeriodMins = Convert.ToInt32(txtGracePeriodMins.Text);
        supplier.Navigator = chkNavigator.Checked;
        supplier.NavRentPrice = Convert.ToDecimal(txtNavRentPrice.Text);
        supplier.NavRentSellPrice = Convert.ToDecimal(txtNavRentSellPrice.Text);
        supplier.NavFixRentPrice = Convert.ToDecimal(txtNavFixRentPrice.Text);
        supplier.NavFixRentSellPrice = Convert.ToDecimal(txtNavFixRentSellPrice.Text);
        supplier.AddDriveRentPrice = Convert.ToDecimal(txtAddDriveRentPrice.Text);
        supplier.AddDriveRentSellPrice = Convert.ToDecimal(txtAddDriveRentSellPrice.Text);

        User user = new User();
        if (supplier.UserId.HasValue && supplier.UserId.Value > 0)
        {
            user = context.Users.SingleOrDefault(u => u.UserId == supplier.UserId.Value);
        }
        else
        {
            user.Password = txtPassword.Text;
            user.UserType = Convert.ToInt16(Enums.UserTypes.Supplier);
            user.Active = true;
        }
        user.Username = txtUsername.Text;
        user.EmailAddress = txtEmailAddress.Text;

        if (!supplier.UserId.HasValue || supplier.UserId.Value == 0)
            context.Users.InsertOnSubmit(user);

        context.SubmitChanges();

        supplier.UserId = user.UserId;

        if (SupplierId == 0)
            context.Suppliers.InsertOnSubmit(supplier);

        context.SubmitChanges();

        Response.Redirect("default.aspx");
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("default.aspx");
    }

    private bool ExistsUsername(string userName, int userId)
    {
        User user = context.Users.SingleOrDefault(u => u.UserId != userId && u.Username == userName);
        return (user != null);
    }
}
